package com.xiaoyao.myframeapp.location;

import android.app.Service;
import android.content.Intent;
import android.location.LocationManager;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.baidu.location.Address;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.xiaoyao.myframeapp.FrameApplication;
import com.xiaoyao.myframeapp.utils.L;
import com.xiaoyao.myframeapp.utils.SpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;


/**
 * Created by Administrator on 2017/3/11 0011.
 */

public class MyLocationServiceService extends Service {
//    public static final String ACTION_LOCATION_SERVICE_SERVICE = "com.roveover.wowo.service.MyLocationServiceService";

    public static String latitude = "39.9";//开始定位位置
    public static String longitude = "116.4";

//    public static String currentLatitude;//当前位置
//    public static String currentLongitude;

    private static final int SCAN_SPAN = 3 * 1000;//TODO 每次自增3秒
    private static final int UPLOAD_TIME = 3 * 60 * 1000;//TODO 每3、5、15分钟上传一次
    private static final int UPLOAD_TIME1 = 5 * 60 * 1000;//TODO 每5分钟 判断一下城市信息
    private static boolean OneUPLOAD_TIME = true;//TODO 默认开始上传一次
    private int time;
    public static boolean isInChina = true; //TODO 中国还是其他地区 true 中国
    public static String city = "";//TODO 城市
    public static String address = "";//地址
    public static Address mAddr;//地址对象

    public LocationClient mLocationClient = null;
    private LocationManager mLocationManager = null;
    private boolean isFirstBDLoc = true;//TODO 是不是百度定位

    //百度定位
    private LocationService locationService;

//    public static MyLocationData MylocData;//当前位置


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        L.e("1111===onCreate==AAAAAAAAAAAAAA");
        //启动定位服务
        initBDLocation();
        super.onCreate();
        //TODO 注册订阅事件
        EventBus.getDefault().register(this);
        L.e("2222===onCreate==AAAAAAAAAAAAAA");
    }

    private void initBDLocation() {
        L.i(getClass(), "1111");
        if (locationService == null) {
            // -----------location config ------------
//            locationService = new LocationService(FrameApplication.getmContext());
            locationService = ((FrameApplication) getApplication()).locationService;
            //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
            locationService.registerListener(mListener);
            //注册监听
            locationService.setLocationOption(locationService.getDefaultLocationClientOption());
            //设置参数
            locationService.start();
            // 定位SDK
            L.i(getClass(), "2222===initBDLocation==start");
        }
    }

    /*****
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            L.i(getClass(), "3333===BDLocationListener");
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                /**
                 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
                 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
                 */
                if (locationService != null) {
                    if (isFirstBDLoc) {

                        //TODO 获取当前定位是国内还是国外
                        //getLocationWhere()
                        if (location.getLocationWhere() == location.LOCATION_WHERE_IN_CN) {
                            isInChina = true;
                            city = location.getCity();
                        } else {
                            isInChina = false;
                            city = "国外";
                        }
                        //TODO 发送广播 当前定位信息
                        EventBus.getDefault().post(
                                new MessageLocationBean("location", isInChina, location));
                    } else {

                    }

                    if (!TextUtils.isEmpty(location.getAddrStr())) {
                        address = location.getAddrStr();
                        mAddr = location.getAddress();
                    } else {
                        address = "空";
                    }
                    latitude = String.valueOf(location.getLatitude());
                    longitude = String.valueOf(location.getLongitude());

                    //TODO 城市位置改变时
                    String City = location.getCity() + "";
                    if (!City.equals(SpUtils.get("City", "北京市").toString())) {
                        SpUtils.put("City", location.getCity() + "");
                    }


                    //TODO 设置当前位置、、简单地址address2。。
                    SpUtils.put("Longitude", longitude);//"116.4"
                    SpUtils.put("Latitude", latitude);//"39.9"
                    SpUtils.put("address", address);//String
//                    }
                    //TODO ===================================================================
                    if (time >= UPLOAD_TIME || OneUPLOAD_TIME) {
                        OneUPLOAD_TIME = false;
                        time = 0;
                        sendLocationToServer(longitude, latitude);//TODO 上传经纬度
                    }
                    time += SCAN_SPAN;

                }

            } else {
                L.i(getClass(), "location.getLocType()" + location.getLocType());
                L.i(getClass(), "或者location=null");
            }
        }

        public void onConnectHotSpotMessage(String s, int i) {
            L.i(getClass(), "4444" + s + ";i=" + i);
        }
    };
    private String userId;
    private UploadLatLonModel uploadLatLonModel = new UploadLatLonModel();
    private boolean uploadLatLonModel_Ok = true;

    private void sendLocationToServer(String Longitude, String Latitude) {

        //TODO 判断是否登陆过true是登陆过（完成）
        if (!(boolean) (SpUtils.get("Login", false))) {
            //TODO 未登录
            return;
        }

        //TODO 上传经纬度
        userId = SpUtils.get("id", 0).toString();
        if (Integer.valueOf(userId) > 0) {
            if (uploadLatLonModel_Ok) {
                uploadLatLonModel_Ok = false;
                uploadLatLonModel.uploadLatLon(Longitude, Latitude, userId, new UploadLatLonModel.InfoHint() {
                    @Override
                    public void success(Boolean isData) {
                        uploadLatLonModel_Ok = true;
                        L.e("位置上传成功");
                    }

                    @Override
                    public void fail(String str) {
                        uploadLatLonModel_Ok = true;
                        L.e("位置上传异常=" + str);
                    }
                });
            }
        }
    }

    private void stopBDLocationClient() {
        if (locationService != null) {
            locationService.unregisterListener(mListener); //注销掉监听
            locationService.stop();
            locationService = null;
            L.i(getClass(), "stop");
        }
    }

    private void stopGoogleLocationManager() {
        if (mLocationManager != null) {
            mLocationManager = null;
        }
    }

    @Override
    public void onDestroy() {
        L.e("onDestroy====BBBBBBBBBBBBBBB");
        super.onDestroy();
        //TODO 取消事件注册
        EventBus.getDefault().unregister(this);
        stopBDLocationClient();
        stopGoogleLocationManager();
    }

    public void startService() {
        startService(new Intent(getApplicationContext(), MyLocationServiceService.class));
        //TODO 开线程操作
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                L.i(getClass(), "启动");
                startService(new Intent(getApplicationContext(), MyLocationServiceService.class));
            }
        }).start();
    }

    /**
     * TODO 收到信息
     *
     * @param message
     */
    @Subscribe
    public void onShowMessageEvent(MessageLocationBean message) {
        String type = message.getType();
        boolean isInChina = message.isInChina();
        switch (type) {
            case "刷新通知":
                break;
            case "获取新通知数量":

                //TODO 发送广播 主界面消息未读数
//                EventBus.getDefault().post(
//                        new MessageHomePage("获取新通知数量", ""));
                break;
        }
    }
}
